<!--Homework 8 Index Page-->

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<HTML>
    <HEAD>
	<TITLE>Movie Search</TITLE>
	<script type="text/javascript">
	function Search(title){
		if (title == ""){
			alert('Please enter the Title')
			return false;
		} else {
			function myCallback() {
			    // only if req shows "loaded"
			    if (req.readyState == 4) {
			        // only if "OK"
			        if (req.status == 200) {
			            // use eval() and responseText methods to retrieve JSON data
			            var doc = eval('(' + req.responseText + ')');
						var resultsNode = doc.results;
						console.log(resultsNode);
						var html_text = "";
						if (resultsNode.result.length == 0){
						html_text = "No Results Found!";
						}
						else {
						html_text = "<table border='2'>";
						
					 	html_text += "<tr><th>Image</th><th>Title</th><th>Year</th><th>Director</th><th>Rating (10)</th><th>Link to Movie</th><th>Post to Facebook</th></tr>";
						for (i=0; i<resultsNode.result.length; i++){
							html_text += "<tr>";
							html_text += "<td align=\"center\">";
							html_text += "<img src=" + resultsNode.result[i].cover + "/>";
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += resultsNode.result[i].title;
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += resultsNode.result[i].year;
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += resultsNode.result[i].director;
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += resultsNode.result[i].rating;
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += "<a href=" + resultsNode.result[i].details + ">details</a>";
							html_text += "</td>";
							html_text += "<td align=\"center\">";
							html_text += "<input type =\"image\" src=\"fblogo.jpg\" width=\"100\" height=\"38\" onClick=\"login(resultsNode.result[i])\"/>";
							html_text += "</td>";	
							html_text += "</tr>";
					}
				}
				
					document.getElementById("results").innerHTML = html_text;
			        } else {
			alert("There was a problem retrieving the XML data:\n"
			+   req.statusText);
			        }
			    }
			}
			
			
			var movie_title = document.getElementsByName("movie_title")[0].value;
			var media_type = document.getElementsByName("media_type")[0].value;
			movie_title = encodeURIComponent(movie_title);
			var url = "http://cs-server.usc.edu:19928/movie_search/MovieSearchServlet?title="+movie_title+"&title_type="+media_type;
			
			var req;
			function loadXMLDoc(url) {
				req = false;
			    // branch for native XMLHttpRequest object
			    if(window.XMLHttpRequest) {
			    	try {
						req = new XMLHttpRequest();
			        } catch(e) {
						req = false;
			        }
			    // branch for IE/Windows ActiveX version
			    } else if(window.ActiveXObject) {
			    	try {
			        	req = new ActiveXObject("Msxml2.XMLHTTP");
			       	} catch(e) {
						try {
			           		req = new ActiveXObject("Microsoft.XMLHTTP");
						} catch(e) {
							req = false;
						}
					}
			    }
				if(req) {
					req.open("GET", url, true); 
					req.onreadystatechange = myCallback; 
					req.setRequestHeader("Connection", "Close"); 
					req.setRequestHeader("Method", "GET" + url + "HTTP/1.1");
					req.send("");
				}
			}
			loadXMLDoc(url);
		}
	}

	
		function testAPI(movie_results) {
		    console.log('Welcome!  Fetching your information.... ');
		    FB.api('/me', function(response) {
		        console.log('Good to see you, ' + response.name + '.');
		    });
		FB.ui(
		  {
		    method: 'feed',
		    name: movie_results.title,
		    link: 'http://developers.facebook.com/docs/reference/dialogs/',
		    picture: 'http://fbrell.com/f8.jpg',
		    caption: 'I am interested in this movie/series/game movie_title released in year has a rating of rating',
		    description: 'Look at user reviews: here'
		  },
		  function(response) {
		    if (response && response.post_id) {
		      alert('Post was published.');
		    } else {
		      alert('Post was not published.');
		    }
		  }
		);

		}

		function login(movie_data) {
		    FB.login(function(response) {
		        if (response.authResponse) {
		            // connected
		                            testAPI(movie_data);
		        } else {
		            // cancelled
		        }
		    });
		}
	</script>
	</HEAD>
	
	<BODY>
		<div id="fb-root"></div>
		<script>
		  // Additional JS functions here
		  window.fbAsyncInit = function() {
		    FB.init({
		      appId      : '247852538673776', // App ID
		      status     : true, // check login status
		      cookie     : true, // enable cookies to allow the server to access the session
		      xfbml      : true  // parse XFBML
		    });

		  };

		  // Load the SDK Asynchronously
		  (function(d){
		     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
		     if (d.getElementById(id)) {return;}
		     js = d.createElement('script'); js.id = id; js.async = true;
		     js.src = "//connect.facebook.net/en_US/all.js";
		     ref.parentNode.insertBefore(js, ref);
		   }(document));
		</script>

	
		
		
		<H1>Movie Search</H1>
		<TABLE BORDER='2' CELLPADDING=10>
			<tr><td align=center>
			<form name="movie_search" id="search">
			Title: <input type="text" name="movie_title" maxlength="255" 
			size="50" value=""/>
			<p>
			Media Type: <select name="media_type">
				  <option selected value="all"> All Types</option>
				  <option value="feature"> Feature Film</option>
				  <option value="tv_series"> TV Series</option>
				  <option value="game"> Video Game</option></select>
			<p>
			<input type="button" name="submit" value="Search" 
			onClick="return Search(this.form.movie_title.value)" />
			</form>
			</tr></td>
		</TABLE>
		<div id="results">
		
		</div>
		<NOSCRIPT>
	</BODY>

</HTML>

